package com.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Desc:
 * @author: lisha 2018/7/27 9:53
 */
public class TestNio {

    public static void main(String[] args) {

        newIo();
        oldIo();
    }

    /**
     * Desc: 使用旧io方式读取
     * @author: lisha 2018/7/27 10:08
     */
    public static void oldIo(){
        String path = "E:\\books.zip";
        try {
            RandomAccessFile file = new RandomAccessFile(path, "rw");
            ByteBuffer buffer1 = ByteBuffer.allocate(1024);
            FileChannel channel = file.getChannel();
            // 普通io流方式
            long startTime =  System.currentTimeMillis();
            while (channel.read(buffer1) > 0){
                buffer1.flip();
                buffer1.clear();
            }

            long endTime = System.currentTimeMillis();
            System.out.println("使用io流方式读取文件总耗时：" + (endTime - startTime));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Desc: 使用new io 方式读取
     * @author: lisha 2018/7/27 10:08
     */
    public static void newIo(){
        String path = "E:\\books.zip";
        try {
            RandomAccessFile file = new RandomAccessFile(path, "rw");
            FileChannel channel = file.getChannel();
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

            long len = file.length();
            long startTime = System.currentTimeMillis();

            // 读取内存映射文件
            for (int i = 0; i < file.length(); i+= 1024*10) {
                if (len - i > 1024){
                    buffer.get(i);
                }
                else {
                    buffer.get(new byte[i - 1024]);
                }
            }
            long endTime = System.currentTimeMillis();
            System.out.println("使用内存映射方式读取文件总耗时： "+(endTime - startTime));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
